package br.com.jk.util;

import br.com.jk.config.Cfg;
import br.com.jk.config.CfgPropUtil;
import br.com.jk.master.MasterSt;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author camilo
 */
public class ReportUtil {

  private static Connection getConnection() throws ClassNotFoundException, SQLException {
    CfgPropUtil propUt = new CfgPropUtil();
    Cfg prop = propUt.getCfgProp();

    String url = "jdbc:postgresql://" + prop.getIp() + ":" + prop.getPorta() + "/" + prop.getNomeBd();
    String user = prop.getUser();
    String password = prop.getPassword();

    Class.forName("org.postgresql.Driver");
    Connection con = DriverManager.getConnection(url, user, password);
    return con;
  }

  public static void getReport(InputStream resource, String title) {
    HashMap map = new HashMap();
    ReportUtil.getReport(resource, title, map);
  }

  public static void getReport(InputStream resource, String title, HashMap parametros) {
    try {
      JasperReport jasperReport = (JasperReport) JRLoader.loadObject(resource);

      JasperPrint jasperPrint;
      jasperPrint = JasperFillManager.fillReport(jasperReport, parametros, ReportUtil.getConnection());

      JasperViewer jrviewer = new JasperViewer(jasperPrint, false);
      jrviewer.setTitle(title);
      jrviewer.setVisible(true);

      MasterSt.setJpbIndeterminate(false);
      MasterSt.setJlStatusMessage("Relatório <" + title + "> gerado com sucesso.");
    } catch (JRException | ClassNotFoundException e) {
      Util.msgErro(e, "Erro ao gerar o relatório");
    } catch (SQLException e){
      Util.msgErro(e, "Erro ao gerar o relatório. Houve problema na conexão com o banco de dados.");
    }
  }
}
